package com.online.taxi.order.implementation.mysql;

import com.online.taxi.order.mapper.TblOrderLockDao;
import com.online.taxi.order.implementation.LockKey;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Data
public class MysqlLock{

	@Autowired
	private TblOrderLockDao mapper;
	
	private ThreadLocal<LockKey> orderLockThreadLocal ;

	public void lock() {
		// 1、尝试加锁
		if(tryLock()) {
			return;
		}
		// 2.休眠
		try {
			Thread.sleep(10);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		// 3.递归再次调用
		lock();
	}
	
	/**
	 * 	非阻塞式加锁，成功，就成功，失败就失败。直接返回
	 */
	public boolean tryLock() {
		try {
			LockKey lockKey = orderLockThreadLocal.get();
			mapper.insertSelective(lockKey);
			return true;
		}catch (Exception e) {
			return false;
		}
	}

	public void unlock() {
		mapper.deleteByPrimaryKey(orderLockThreadLocal.get().getOrderId());
		orderLockThreadLocal.remove();
	}


}
